<template>
  <el-dialog
    v-el-drag-dialog
    title="瓶批单"
    :visible.sync="visible"
    width="1024px"
    @closed="resetData"
  >
    <el-form ref="dataForm" class="form" :model="temp" label-position="right" label-width="80px">
      <el-form-item label="责任机构:" prop="orgName">
        <el-input v-model="userInfo.orgName" disabled />
      </el-form-item>
      <el-form-item label-width="0">
        <el-input v-model.trim="csmText" placeholder="请输入">
          <el-select slot="prepend" v-model="qtype" style="width: 100px;" placeholder="请选择">
            <el-option label="客户编号" value="csmCode" />
            <el-option label="客户电话" value="csmRgPhone" />
            <el-option label="客户名称" value="csmName" />
          </el-select>
        </el-input>
      </el-form-item>
      <el-form-item label-width="0">
        <div>
          <el-button slot="append" class="append-search" @click="search">查询</el-button>
          <el-button slot="append" class="append-search" @click="clearData">重置</el-button>
        </div>
      </el-form-item>
      <el-form-item label="客户:" prop="csmName">
        <el-input v-model="temp.csmName" disabled />
      </el-form-item>
      <el-form-item v-show="temp.cardSurplus" label="预付卡余额:" prop="cardSurplus" label-width="95px">
        <el-input v-model="temp.cardSurplus" disabled />
      </el-form-item>
      <el-form-item label="电话:" prop="contactPhone">
        <el-select v-model="temp.contactPhone">
          <el-option v-for="item in phoneList" :key="item.csmPhone" :value="item.csmPhone" :label="item.csmPhone" />
        </el-select>
      </el-form-item>
      <el-form-item label="地址:" prop="csmAddressId">
        <el-select v-model="temp.csmAddressId">
          <el-option v-for="item in csmAddressList" :key="item.csmAddressId" :value="item.csmAddressId" :label="item.csmAddress" />
        </el-select>
      </el-form-item>
      <el-form-item label="批发类型:" prop="wsaleType">
        <el-select v-model="temp.wsaleType" placeholder="请选择">
          <el-option
            v-for="item in wsaleTypeBottleMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="配送车辆:" prop="truckNo">
        <el-select v-model="temp.truckNo" placeholder="请选择" clearable @change="truckChange">
          <el-option
            v-for="item in truckList"
            :key="item.truckId"
            :label="item.truckCode"
            :value="item.truckCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="运费:" prop="decimalSpare1">
        <!-- <el-input v-model="temp.decimalSpare1" :max="10000" @input="temp.decimalSpare1=temp.decimalSpare1.replace(/[^\d.]/g, '').replace(/^0\d+|^\./g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(.*\..{2}).*$/,'$1')" @blur="onBlur" /> -->
        <el-input-number v-model="temp.decimalSpare1" :controls="false" :min="0" :max="10000" :precision="2" style="width: 100%;" />
      </el-form-item>
      <el-form-item label="司机:" prop="driver">
        <el-select v-model="temp.driver" multiple placeholder="请选择" clearable>
          <el-option
            v-for="item in driverList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="押运员:" prop="escortName">
        <el-select v-model="temp.escortName" multiple placeholder="请选择" clearable>
          <el-option
            v-for="item in escortList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注:" prop="remark" class="block">
        <el-input v-model="temp.remark" type="textarea" :rows="3" maxlength="255" show-word-limit />
      </el-form-item>
      <el-form-item label="商品分类:" prop="goodsTypeObj" style="width: 42%;">
        <el-select v-model="temp.goodsTypeObj" value-key="gtId" :loading="$loadingPlugin.getGoodsTypeFn" filterable placeholder="请选择" clearable style="width: 100%;" @change="goodsTypeChange">
          <el-option
            v-for="item in goodsTypeList"
            :key="item.gtId"
            :label="item.gtName"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品列表:" prop="goodsByTypeObj" style="width: 42%;">
        <el-select v-model="temp.goodsByTypeObj" value-key="goodsId" :loading="$loadingPlugin.getGoodsList" filterable placeholder="请选择" clearable style="width: 100%;" @change="goodsChange">
          <el-option
            v-for="item in goodsByTypeList"
            :key="item.goodsId"
            :label="item.goodsName"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label-width="0" style="width: 2%;">
        <el-button type="primary" size="mini" @click="addGoods">添加</el-button>
      </el-form-item>
    </el-form>
    <lb-table
      ref="lbTable"
      border
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      :immediate-fetch="false"
      :summary-method="getSummaries"
      show-summary
      highlight-current-row
    />
    <to-pay ref="toPay" />
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        取消
      </el-button>
      <el-button :loading="$loadingPlugin.success" type="primary" @click="success">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import {
    wsaleCsmInfo,
    queryTruckList,
    queryDriverList,
    queryEscortList,
    goodsTypeQueryAllList,
    queryGoodsByType,
    saveLorryOrderDropIn,
    querySelectGoodsPrice, queryWsaleOrderBillDetail
  } from '@/api'
  import { mapGetters } from 'vuex'
  import { accDiv, accMul } from '@/utils/math'
  // import { formatFixed2 } from '@/utils'
  import ToPay from './ToPay'

  export default {
    name: 'add-bottle-order',
    components: {
      ToPay
    },
    data() {
      return {
        visible: false,
        csmText: '',
        qtype: 'csmCode',
        wsaleTypeBottleMap: [{ 'value': 1, 'desc': '预约批发', 'key': 'TYPE1' }, { 'value': 2, 'desc': '上门批发', 'key': 'TYPE2' }],
        csmInfo: undefined,
        phoneList: [],
        csmAddressList: [],
        truckList: [],
        driverList: [],
        escortList: [],
        goodsTypeList: [],
        goodsByTypeList: [],
        temp: {
          csmSearchType: 'csmPhone',
          csmAddressId: '',
          csmName: '',
          csmId: '',
          csmCode: '',
          contactPhone: '',
          wsaleType: 2,
          truckNo: '',
          decimalSpare1: '',
          driver: [],
          escortName: [],
          remark: '',
          goodsTypeObj: undefined,
          goodsByTypeObj: undefined
        },
        selectGoods: undefined,
        goodsSum: 0,
        tableData: {
          data: [],
          column: [
            {
              prop: 'goodsName',
              label: '商品'
            },
            {
              prop: 'specName',
              label: '规格型号'
            },
            {
              prop: 'gCount',
              label: '数量',
              align: 'right',
              render: (h, scope) => scope.row._edit ? <el-input v-model={scope.row[scope.column.property]} onInput={val => scope.row[scope.column.property] = val.replace(/[^-?\d]/g, '').replace(/^-?0+/g, '')} onBlur={(val) => { this.gcountblurInput(scope.row, scope.column, val) }} maxLength='4' size='mini' /> : <span>{ scope.row[scope.column.property]}</span>
            },
            {
              prop: 'gdWeight',
              label: '每瓶重量(kg)',
              align: 'right',
              // formatter: row => formatFixed2(row.gdWeight),
              // render: (h, scope) => scope.row._edit && scope.row.pricingMode === 2 ? <el-input v-model={scope.row[scope.column.property]} onInput={val => scope.row[scope.column.property] = val.replace(/[^\d.]/g, '').replace(/^0\d+|^\./g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(.*\..{2}).*$/, '$1')} size='mini' /> : <span>{ scope.row[scope.column.property]}</span>
              render: (h, scope) => scope.row._edit ? <el-input-number v-model={scope.row[scope.column.property]} controls={false} min={0} max={10000} precision={2} size='mini' onBlur={(val) => { this.gdWeightInput(scope.row, scope.column, val) }}/> : <span>{ scope.row[scope.column.property]}</span>
            },
            {
              prop: 'netWeight',
              label: '总重量(吨)',
              align: 'right'
            },
            {
              prop: 'gPrice',
              label: '单价',
              align: 'right',
              render: (h, scope) => scope.row._edit ? <el-input-number v-model={scope.row[scope.column.property]} controls={false} min={0} max={10000} precision={2} size='mini' /> : <span>{ scope.row[scope.column.property]}</span>
            },
            {
              prop: 'tReceivable',
              label: '金额',
              align: 'right'
            },
            {
              label: '操作',
              align: 'center',
              fixed: 'right',
              width: 80,
              render: (h, scope) => {
                return (
                  scope.row._edit ? <div>
                    <el-link type='primary' underline={false} size='mini' onClick={() => this.saveRow(scope)}>
                      保存
                    </el-link>
                    <el-link size='mini' type='danger' underline={false} onClick={() => this.delRow(scope)}>
                      删除
                    </el-link>
                  </div> : <div>
                    <el-link type='primary' underline={false} size='mini' onClick={() => this.editRow(scope)}>
                      编辑
                    </el-link>
                    <el-link size='mini' type='danger' underline={false} onClick={() => this.delRow(scope)}>
                      删除
                    </el-link>
                  </div>
                )
              }
            }
          ]
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'userInfo'
      ])
    },
    watch: {
      // 'temp.driver': function(val, oldval) {
      //   const newindex = val.indexOf(0)
      //   const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
      //   if (newindex !== -1 && oldindex === -1 && val.length > 1) { // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
      //     this.temp.driver = [0]
      //   } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) { // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
      //     this.temp.driver.splice(val.indexOf(0), 1)
      //   }
      //   if (this.temp.driver.length === 0) this.temp.driver = '' // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      // },
      // 'temp.escortName': function(val, oldval) {
      //   const newindex = val.indexOf(0)
      //   const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
      //   if (newindex !== -1 && oldindex === -1 && val.length > 1) { // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
      //     this.temp.escortName = [0]
      //   } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) { // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
      //     this.temp.escortName.splice(val.indexOf(0), 1)
      //   }
      //   if (this.temp.escortName.length === 0) this.temp.escortName = '' // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      // }
    },
    methods: {
      async open(temp) {
        await Promise.all([this.getTruckList(), this.getDriverList(), this.getEscortList(), this.getGoodsTypeFn()])
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          this.temp.wsaleType = 2
          this.tableData.data = []
          if (temp) {
            this.temp = Object.assign(this.temp, temp)
          }
        })
      },
      // 查询配送车辆列表
      async getTruckList() {
        const res = await queryTruckList()
        console.log('运输车辆', res)
        this.truckList = res.data
      },
      // 查询司机列表
      async getDriverList() {
        const res = await queryDriverList()
        this.driverList = res.data
      },
      // 查询押运员列表
      async getEscortList() {
        const res = await queryEscortList()
        this.escortList = res.data
      },
      // 查询商品分类下拉列表
      async getGoodsTypeFn() {
        const res = await goodsTypeQueryAllList({
        })
        this.goodsTypeList = res.data
        if (res.data.length > 0) {
          this.temp.goodsTypeObj = res.data[0]
          this.getGoodsList(res.data[0].gtId)
        }
      },
      // 查询
      async search() {
        if (!this.csmText) {
          this.$message.error('查询条件不能为空!')
          return
        }
        const params = {
          csmStatus: 9, // 查询状态不是已注销的客户
          csmType: 8 // 瓶批客户
        }
        params[this.qtype] = this.csmText
        const res = await wsaleCsmInfo(params)
        if (!res.data || res.data.csmType !== 8) {
          this.$message.error('此用户不是瓶批用户')
          return
        }
        this.csmInfo = res.data
        let isChangeCustom = false
        if (this.temp.csmId !== 0) {
          if (this.temp.csmId !== this.csmInfo.csmId) {
            // 说明客户没有改变
            isChangeCustom = true
          }
        }
        this.temp.csmName = this.csmInfo.csmName
        this.temp.cardSurplus = (this.csmInfo.cardSurplus / 100).toFixed(2)
        // 电话
        this.phoneList = this.csmInfo.phoneItems.filter(item => item.cpStatus === 2)
        if (this.phoneList.length) {
          this.temp.contactPhone = this.phoneList[0].csmPhone
        }
        this.temp.csmId = this.csmInfo.csmId // 客户id
        this.temp.csmCode = this.csmInfo.csmCode // 客户编号
        this.temp.csmType = this.csmInfo.csmType // 客户类型
        // 地址
        this.csmAddressList = this.csmInfo.addressItems
        if (this.csmAddressList.length) {
          this.temp.csmAddressId = this.csmInfo.addressItems[0].csmAddressId
        }
        if (this.phoneList && this.phoneList.length > 0) {
          if (this.temp.csmSearchType === 'csmPhone') { // 说明电话查找
            this.phoneList.forEach(item => {
              if (item.csmPhone === this.csmText) {
                this.$set(this.temp, 'csmPhone', item.csmPhone)
              }
            })
          } else {
            this.$set(this.temp, 'csmPhone', this.phoneList[0].csmPhone)
          }
        }
        if (this.tableData.data.length !== 0 && isChangeCustom) {
          this.$message.info('客户发生变化对应的区域价格可能发生变化,商品需重新选择')
          // 清空表格商品
          this.$set(this.tableData, 'data', [])
        }
      },
      // 添加商品
      async addGoods() {
        if (!this.temp.goodsTypeObj || !this.temp.goodsByTypeObj) {
          this.$message.error('请选择商品类别及商品！')
          return
        }
        if (!this.csmInfo) {
          this.$message.error('请选择客户！')
          return
        }
        // 查询当前商品详情
        const res = await querySelectGoodsPrice({
          goodsCode: this.temp.goodsByTypeObj.goodsCode,
          orgSNNo: this.userInfo.orgSNNo,
          csmId: this.temp.csmId,
          csmType: this.temp.csmType
        })
        this.selectGoods = res.data
        let sign = true
        // var tReceivable = 0
        // if (this.selectGoods.pricingMode === 1) { // 说明是按包装计价
        //   tReceivable = this.selectGoods.basePrice.toFixed(2)
        // } else if (this.selectGoods.pricingMode === 2) { // 说明是按单位计价
        //   tReceivable = accMul(this.selectGoods.basePrice, this.selectGoods.weight).toFixed(2)
        // }
        // if (this.tableData.data.some(item => item.goodsName === this.temp.goodsByTypeObj.goodsName)) {
        //   const copy = JSON.parse(JSON.stringify(this.tableData.data))
        //   const match = copy.find(item => item.goodsName === this.temp.goodsByTypeObj.goodsName)
        //   match.gCount++
        //   const index = copy.findIndex(item => item.goodsName === this.temp.goodsByTypeObj.goodsName)
        //   copy.splice(index, 1, match)
        //   this.$set(this.tableData, 'data', copy)
        // }
        if (this.tableData.data.length !== 0) {
          this.tableData.data.forEach(item => {
            if (this.temp.goodsByTypeObj.goodsCode === item.goodsCode) {
              sign = false
              item.gCount++
              item.tReceivable = (item.gCount * item.gPrice).toFixed(2)
            }
          })
        }

        if (sign) {
          this.tableData.data.push(
            {
              gtId: this.temp.goodsTypeObj.gtId,
              gtFlag: this.temp.goodsTypeObj.gtFlag,
              goodsId: this.temp.goodsByTypeObj.goodsId,
              goodsCode: this.temp.goodsByTypeObj.goodsCode,
              goodsName: this.temp.goodsByTypeObj.goodsName,
              specName: this.temp.goodsByTypeObj.specName,
              gdProperty: this.selectGoods.gdProperty,
              gdWeight: (this.selectGoods.weight).toFixed(2),
              gPrice: (this.selectGoods.basePrice).toFixed(2),
              gCount: 1,
              netWeight: Number(accDiv(this.selectGoods.weight, 1000)).toFixed(5),
              tReceivable: (1 * (this.selectGoods.basePrice * 1)).toFixed(2),
              specCode: this.temp.goodsByTypeObj.specCode,
              specAlias: this.temp.goodsByTypeObj.specAlias,
              pricingMode: this.temp.goodsByTypeObj.pricingMode
            }
          )
        }
      },
      // 编辑行
      async editRow(scope) {
        this.$set(scope.row, '_edit', true)
      },
      // 数量改变
      gcountblurInput(row) {
        var reg = /^\+?[0-9]\d*$/
        var flag = reg.test(row.gCount)
        if (!row.gCount) {
          row.gCount = 0
        }
        if (!flag && row.gCount) {
          this.$message.warning(`只能输入数字，请重新输入`)
          row.gCount = 0
          return
        }
        if (row.gCount > 99999) {
          row.gCount = 99999
        }
        row.netWeight = (Number(row.gCount) * Number(row.gdWeight) / 1000).toFixed(5)
        this.$nextTick(() => {
          this.tableData.data = [...this.tableData.data]
        })
      },
      // 重量改变
      gdWeightInput(row) {
        row.netWeight = (Number(row.gCount) * Number(row.gdWeight) / 1000).toFixed(5)
        this.$nextTick(() => {
          this.tableData.data = [...this.tableData.data]
        })
      },
      // 保存行
      saveRow(scope) {
        let tReceivable = 0
        if (!scope.row.gCount) {
          this.$message.error('请填写商品数量')
          return
        }
        this.$set(scope.row, '_edit', false)
        if (scope.row.pricingMode === 1) { // 说明是按包装计价
          tReceivable = accMul(scope.row.gPrice, scope.row.gCount).toFixed(2)
        } else if (scope.row.pricingMode === 2) { // 说明是按单位计价
          tReceivable = accMul(scope.row.gCount, scope.row.gdWeight * scope.row.gPrice).toFixed(2)
        }
        scope.row.tReceivable = tReceivable
        this.$set(this.tableData.data, scope.$index, JSON.parse(JSON.stringify(scope.row)))
      },
      // 删除行
      delRow(scope) {
        this.tableData.data.splice(scope.$index, 1)
      },
      // 商品类型改变
      async goodsTypeChange(obj) {
        this.temp.goodsByTypeObj = undefined
        this.getGoodsList(obj.gtId || 0)
      },
      // 查询商品列表
      async getGoodsList(gtId) {
        const res = await queryGoodsByType({
          gTypeId: gtId
        })
        this.goodsByTypeList = res.data
        if (res.data && res.data.length > 0) {
          this.temp.goodsByTypeObj = res.data[0]
        }
      },
      // 商品改变
      async goodsChange(obj) {
        this.temp.goodsByTypeObj = obj
      },
      // 合计方法
      getSummaries(param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计'
            return
          }
          if (column.property === 'gdWeight' || column.property === 'gPrice') {
            return
          }
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
          }
        })
        if (sums.length > 6) {
          sums[4] = sums[4].toFixed(5)
          sums[6] = sums[6].toFixed(2)
          this.goodsSum = sums[6]
        }
        return sums
      },
      success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          if (!this.rules()) return
          const matchAddress = this.csmAddressList.find(item => item.csmAddressId === this.temp.csmAddressId)
          const params = {
            orgId: this.userInfo.orgId,
            orgName: this.userInfo.orgName,
            orgSNNo: this.userInfo.orgSNNo,
            csmId: this.csmInfo.csmId,
            csmName: this.csmInfo.csmName,
            csmCode: this.csmInfo.csmCode,
            contactPhone: this.temp.contactPhone,
            contact: this.csmInfo.csmName,
            csmAddressId: matchAddress.csmAddressId,
            csmAddress: matchAddress.csmAddress,
            csmType: this.csmInfo.csmType,
            wsaleFlag: 1,
            decimalSpare1: (this.temp.decimalSpare1 * 1).toFixed(2),
            truckNo2: this.temp.wsaleType === 1 ? '' : this.temp.truckNo, // 上门批发车牌号,预约批发，上门批发车牌号为空
            wsaleType: this.temp.wsaleType,
            truckNo: this.temp.truckNo,
            driver: this.temp.driver.join(','),
            escortName: this.temp.escortName.join(','),
            remark: this.temp.remark
          }
          params.orderWsaleOrderDetailInfoList = this.tableData.data.map(item => {
            return { ...item }
          })
          // 处理商品列表描述
          var describe = []
          this.tableData.data.map(l => {
            const mag = l.goodsName + '^' + l.gPrice + '^' + l.gCount
            describe.push(mag)
          })
          params.goodsDesc = describe.join(';')
          // 商品总数量
          var num = 0
          this.tableData.data.map(l => {
            num += (l.gCount * 1)
          })
          params.goodsCount = num
          // 订单总额
          var price = 0
          this.tableData.data.map(l => {
            price += (l.tReceivable * 1)
          })
          params.decimalSpare4 = (price + this.temp.decimalSpare1).toFixed(2)
          params.tReceivables = (price + this.temp.decimalSpare1).toFixed(2)
          if (this.temp.wsaleType === 1) { // 预约批发
            this.$confirm('确认保存当前预约瓶批单？', '提示', {
              type: 'warning'
            }).then(() => {
              const loading = this.$message({
                message: '正在执行操作',
                duration: 0,
                iconClass: 'el-icon-loading'
              })
              saveLorryOrderDropIn(params).then((res) => {
                console.log('res', res)
                this.$notify({
                  title: '提示',
                  message: '保存成功',
                  type: 'success',
                  duration: 2000
                })
                this.visible = false
                this.resolve()
                // 更新数据
                this.$emit('upDataTable')
              }).finally(() => {
                loading.close()
              })
            })
          } else if (this.temp.wsaleType === 2) { // 上门批发
            this.$confirm('确认保存当前上门瓶批单？', '提示', {
              type: 'warning'
            }).then(() => {
              const loading = this.$message({
                message: '正在执行操作',
                duration: 0,
                iconClass: 'el-icon-loading'
              })
              saveLorryOrderDropIn(params).then(async(res) => {
                this.$notify({
                  title: '提示',
                  message: '保存成功',
                  type: 'success',
                  duration: 2000
                })
                const detail = await queryWsaleOrderBillDetail({
                  orderCode: res.data
                })
                this.$refs.toPay.open(detail.data, params.decimalSpare4)
                this.visible = false
                this.resolve()
              }).finally(() => {
                loading.close()
              })
            })
          }
        })
      },
      // 车辆切换设置司机和押运员
      truckChange(val) {
        if (val) {
          const truckInfo = this.truckList.find(l => l.truckCode === val)
          this.temp.driver = truckInfo.driverNames ? truckInfo.driverNames.split(',') : []
          this.temp.escortName = truckInfo.escortNames ? truckInfo.escortNames.split(',') : []
          const driver = []
          const escortName = []
          this.temp.driver.forEach((item) => {
            let has = false
            this.driverList.forEach((item2) => {
              if (item === item2.userName) {
                has = true
              }
            })
            if (has) {
              driver.push(item)
            }
          })
          this.temp.escortName.forEach((item) => {
            let has = false
            this.escortList.forEach((item2) => {
              if (item === item2.userName) {
                has = true
              }
            })
            if (has) {
              escortName.push(item)
            }
          })
          this.temp.driver = driver
          this.temp.escortName = escortName
        } else {
          this.temp.driver = []
          this.temp.escortName = []
        }
      },
      // 统一校验
      rules() {
        if (!this.temp.csmName) {
          this.$message.error('未获取客户名称!')
          return false
        }
        // if (!this.temp.truckNo) {
        //   this.$message.error('请选择车辆')
        //   return false
        // }
        // if (!this.temp.decimalSpare1) {
        //   this.$message.error('请输入运费')
        //   return false
        // }
        // if (!this.temp.driver.length) {
        //   this.$message.error('请选择司机')
        //   return false
        // }
        // if (!this.temp.escortName.length) {
        //   this.$message.error('请选择押运员')
        //   return false
        // }
        if (!this.tableData.data.length) {
          this.$message.error('请添加商品')
          return
        }
        if (this.tableData.data.some(item => item._edit)) {
          this.$message.error('请结束编辑！')
          return false
        }
        return true
      },
      // 格式化金额
      onBlur(e) {
        if (e.target.value) {
          e.target.value = (e.target.value * 1).toFixed(2)
        }
      },
      // 重置数据
      clearData() {
        this.csmText = ''
        this.temp.csmName = ''
        this.phoneList = []
        this.temp.contactPhone = ''
        this.csmAddressList = []
        this.temp.csmAddressId = ''
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      },
      resetData() {
        this.visible = false
        this.csmText = ''
        this.qtype = 'csmCode'
        this.csmInfo = undefined
        this.phoneList = []
        this.csmAddressList = []
        this.truckList = []
        this.driverList = []
        this.escortList = []
        this.goodsTypeList = []
        this.goodsByTypeList = []
        this.temp = {
          csmSearchType: 'csmPhone',
          csmAddressId: '',
          csmName: '',
          csmId: '',
          csmCode: '',
          contactPhone: '',
          wsaleType: 2,
          truckNo: '',
          decimalSpare1: '',
          driver: [],
          escortName: [],
          remark: '',
          goodsTypeObj: undefined,
          goodsByTypeObj: undefined
        }
        this.selectGoods = undefined
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 33.3%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
</style>
